# -*- coding: utf-8 -*-
"""
Small utilities.
"""
from datetime import datetime
from mercurial import util as mercutil
import re

_REPLACEMENTS = {
            " " : "_",
            "-" : "_",
            ":" : "_",
            "/" : "_",
            "\\" : "_",
         }

def replace_all(text, chars):
    """
    Replaces all special characters to file name friendly.
    """
    for i, j in chars.iteritems():
        text = text.replace(i, j)
    return text


def get_repo_file_name(location):
    """
    Produces file name friendly representation of the location.
    """
    return replace_all(location, _REPLACEMENTS)


def get_current_time_file_string():
    """
    Returns current time as file name friendly string.
    """
    return replace_all(str(datetime.now()), _REPLACEMENTS)

def get_mail(settings, user):
    """
    Retrieves mail from user name.
    
    Performs some intelligent mapping. Tries to find mapping in mapping dictionary as is, 
    then as lowercase. Then sees if it already contains domain. If not checks if it 
    looks like user name and adds domain if it does.
    """
    email = mercutil.email(user)
    email = settings.USER_EMAIL_MAPPER[email] \
        if email in settings.USER_EMAIL_MAPPER else email
    email = email.lower()
    email = settings.USER_EMAIL_MAPPER[email] \
        if email in settings.USER_EMAIL_MAPPER else email
    email = settings.USER_EMAIL_MAPPER[email.split("@")[0]] \
        if email.split("@")[0] in settings.USER_EMAIL_MAPPER else email
    if settings.USER_DOMAIN in email:
        return email
    if re.match(settings.USER_REGEXP, email):
        email = email + settings.USER_DOMAIN
    else:
        email = None
    return email
